package com.xpq.petserver.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xpq.petserver.entity.DO.BailmentData;
import com.xpq.petserver.entity.DO.Picture;
import com.xpq.petserver.entity.DO.User;
import com.xpq.petserver.entity.DTO.PublicFosterageDTO;
import com.xpq.petserver.entity.DTO.SearchBailmentDataDTO;
import com.xpq.petserver.entity.VO.BailmentDetailVO;
import com.xpq.petserver.entity.VO.MyFosterageVO;
import com.xpq.petserver.entity.VO.SearchBailmentDataVO;
import com.xpq.petserver.entity.response.GeneralResponse;
import com.xpq.petserver.mapper.BailmentDataMapper;
import com.xpq.petserver.mapper.PictureMapper;
import com.xpq.petserver.mapper.UserMapper;
import com.xpq.petserver.service.BailmentDataService;
import com.xpq.petserver.util.GetTimeUtils;
import com.xpq.petserver.util.PathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 寄养数据相关业务
 * @author XPQ
 * @date 2022-05-03
 */
@Service
public class BailmentDataServiceImpl implements BailmentDataService {
    @Autowired
    private BailmentDataMapper bailmentDataMapper;
    @Autowired
    private PictureMapper pictureMapper;
    @Autowired
    private UserMapper userMapper;
    /**
     * 发布寄养消息业务
     * @param multipartFiles
     * @param publicFosterageDTO
     * @return
     */
    @Override
    @Transactional
    public GeneralResponse publicFosterage(List<MultipartFile> multipartFiles, PublicFosterageDTO publicFosterageDTO) {
        GeneralResponse generalResponse = new GeneralResponse();
        // 整理寄养消息数据
        long bailmentDataId = System.currentTimeMillis();
        publicFosterageDTO.setId(bailmentDataId);
        publicFosterageDTO.setCreateTime(GetTimeUtils.getCurrentTime());
        publicFosterageDTO.setUpdateTime(GetTimeUtils.getCurrentTime());

        // 整理图片数据
        List<Picture> pictures = new ArrayList<>();
        for (int i=0; i < multipartFiles.size(); i++) {
            Picture picture = new Picture();
            picture.setId(System.currentTimeMillis() + i);
            picture.setFilename(System.currentTimeMillis() + i + multipartFiles.get(i).getOriginalFilename());
            picture.setBailmentDataId(bailmentDataId);
            picture.setCreateTime(GetTimeUtils.getCurrentTime());
            picture.setUpdateTime(GetTimeUtils.getCurrentTime());
            pictures.add(picture);
        }

        try {
            // 向数据库添加数据和将文件存储到硬盘
            publicFosterageDTO.setIsDelete("0");
            String code = String.format("%04d",new Random().nextInt(9999));
            publicFosterageDTO.setCode(code);
            bailmentDataMapper.insertBailmentData(publicFosterageDTO);
            if(pictures.size() != 0) {
                pictureMapper.insertPicture(pictures);

                // 判断文件夹是否存在
                File fileDir = new File(PathUtils.getPicturePhysicalPath());
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                for (int i = 0; i < pictures.size(); i++) {
                    File file = new File(fileDir, pictures.get(i).getFilename());
                    boolean isSuccessfullyNewFile = file.createNewFile();
                    if(isSuccessfullyNewFile) {
                        multipartFiles.get(i).transferTo(file);
                    }
                }
            }
            generalResponse.setCode(200);
            generalResponse.setMsg("发布成功！");
        } catch (IOException e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("图片上传出错！");
        } catch (Exception e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("发布失败！");
        }

        return generalResponse;
    }

    /**
     * 编辑寄养消息业务
     * @param multipartFiles
     * @param publicFosterageDTO
     * @return
     */
    @Override
    @Transactional
    public GeneralResponse publicFosterageEdit(List<MultipartFile> multipartFiles, PublicFosterageDTO publicFosterageDTO) {
        GeneralResponse generalResponse = new GeneralResponse();
        // 整理寄养消息数据
        publicFosterageDTO.setCreateTime(GetTimeUtils.getCurrentTime());
        publicFosterageDTO.setUpdateTime(GetTimeUtils.getCurrentTime());

        // 整理图片数据
        List<Picture> pictures = new ArrayList<>();
        for (int i=0; i < multipartFiles.size(); i++) {
            Picture picture = new Picture();
            picture.setId(System.currentTimeMillis() + i);
            picture.setFilename(System.currentTimeMillis() + i + multipartFiles.get(i).getOriginalFilename());
            picture.setBailmentDataId(publicFosterageDTO.getId());
            picture.setCreateTime(GetTimeUtils.getCurrentTime());
            picture.setUpdateTime(GetTimeUtils.getCurrentTime());
            pictures.add(picture);
        }

        try {
            // 向数据库添加数据和将文件存储到硬盘
            bailmentDataMapper.updateBailmentData(publicFosterageDTO);
            if(pictures.size() != 0) {
                pictureMapper.insertPicture(pictures);

                // 判断文件夹是否存在
                File fileDir = new File(PathUtils.getPicturePhysicalPath());
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                for (int i = 0; i < pictures.size(); i++) {
                    File file = new File(fileDir, pictures.get(i).getFilename());
                    boolean isSuccessfullyNewFile = file.createNewFile();
                    if(isSuccessfullyNewFile) {
                        multipartFiles.get(i).transferTo(file);
                    }
                }
            }
            generalResponse.setCode(200);
            generalResponse.setMsg("编辑成功！");
        } catch (IOException e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("图片上传出错！");
        } catch (Exception e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("编辑失败！");
        }

        //删除旧图片数据
        try {
            List<String> filenames = pictureMapper.selectFilenames(publicFosterageDTO.getId());
            for (int i = 0; i < filenames.size(); i++) {
                File file = new File(PathUtils.getPicturePhysicalPath() + filenames.get(i));
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("删除旧图片失败！");
        }

        return generalResponse;
    }


    /**
     * 获取用户寄养数据
     * @param userId 用户id
     * @return
     */
    @Override
    public GeneralResponse getMyFosterage(String userId, Integer pageNum, Integer pageSize) {
        GeneralResponse generalResponse = new GeneralResponse();

        try {
            User user = userMapper.selectUserById(userId);
            String isDelete = "0";
            if(user != null && "2".equals(user.getRole())){
                isDelete = "";
            }
            PageHelper.startPage(pageNum, pageSize);
            List<MyFosterageVO> myFosterageVOs = bailmentDataMapper.selectMyFosterage(userId, isDelete);
            PageInfo<MyFosterageVO> myFosterageVOPageInfo = new PageInfo<>(myFosterageVOs);

            // 获取每条寄养数据的第一张图片
            for (int i = 0; i < myFosterageVOPageInfo.getList().size(); i++) {
                String filename = pictureMapper.selectFistFilename( myFosterageVOPageInfo.getList().get(i).getId());
                if (filename != null) {
                    myFosterageVOPageInfo.getList().get(i).setPicture(PathUtils.getPictureLogicalPath() + filename);
                }
            }
            generalResponse.setCode(200);
            generalResponse.setMsg("获取数据成功！");
            generalResponse.setData(myFosterageVOPageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("获取数据失败！");
        }

        return generalResponse;
    }
    /**
     * 获取全部寄养数据
     * @return
     */
    @Override
    public GeneralResponse getMyFosterageAll(String userId, Integer pageNum, Integer pageSize) {
        GeneralResponse generalResponse = new GeneralResponse();

        try {
            User user = userMapper.selectUserById(userId);
            String isDelete = "0";
            if(user != null && "2".equals(user.getRole())){
                isDelete = "";
            }
            PageHelper.startPage(pageNum, pageSize);
            List<MyFosterageVO> myFosterageVOs = bailmentDataMapper.selectMyFosterageAll(isDelete);
            PageInfo<MyFosterageVO> myFosterageVOPageInfo = new PageInfo<>(myFosterageVOs);

            // 获取每条寄养数据的第一张图片
            for (int i = 0; i < myFosterageVOPageInfo.getList().size(); i++) {
                String filename = pictureMapper.selectFistFilename( myFosterageVOPageInfo.getList().get(i).getId());
                if (filename != null) {
                    myFosterageVOPageInfo.getList().get(i).setPicture(PathUtils.getPictureLogicalPath() + filename);
                }
            }
            generalResponse.setCode(200);
            generalResponse.setMsg("获取数据成功！");
            generalResponse.setData(myFosterageVOPageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("获取数据失败！");
        }

        return generalResponse;
    }


    /**
     * 更新寄养信息为已领养
     * @param id 寄养消息id
     * @return
     */
    @Override
    public GeneralResponse updateBailmentDetailAdopt(Long id, String code) {
        GeneralResponse generalResponse = new GeneralResponse();

        try {
            BailmentDetailVO bailmentDetailVO = bailmentDataMapper.getBailmentDetailCode(id, code);
            if(bailmentDetailVO != null && bailmentDetailVO.getId() != null && !("".equals(bailmentDetailVO.getId()))){
                bailmentDataMapper.updateBailmentDetailAdopt(id, code);
                generalResponse.setCode(200);
                generalResponse.setMsg("更新成功！");
            }else{
                generalResponse.setCode(500);
                generalResponse.setMsg("验证码无效！");
            }


        } catch (Exception e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("更新失败！");
        }

        return generalResponse;
    }

    /**
     * 获取寄养消息的详情信息-无验证码
     * @param id 寄养消息id
     * @return
     */
    @Override
    public GeneralResponse getBailmentDetail(Long id) {
        GeneralResponse generalResponse = new GeneralResponse();

        try {
            BailmentDetailVO bailmentDetailVO = bailmentDataMapper.selectBailmentDetail(id);
            List<String> filenames = pictureMapper.selectFilenames(id);
            for (int i = 0; i < filenames.size(); i++) {
                filenames.set(i, PathUtils.getPictureLogicalPath()+filenames.get(i));
            }
            bailmentDetailVO.setPictures(filenames);
            generalResponse.setCode(200);
            generalResponse.setMsg("获取数据成功！");
            generalResponse.setData(bailmentDetailVO);
        } catch (Exception e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("获取数据失败！");
        }

        return generalResponse;
    }

    /**
     * 获取寄养消息的详情信息-有验证码
     * @param id 寄养消息id
     * @return
     */
    @Override
    public GeneralResponse getBailmentDetailCode(Long id) {
        GeneralResponse generalResponse = new GeneralResponse();

        try {
            BailmentDetailVO bailmentDetailVO = bailmentDataMapper.selectBailmentDetailCode(id);
            List<String> filenames = pictureMapper.selectFilenames(id);
            for (int i = 0; i < filenames.size(); i++) {
                filenames.set(i, PathUtils.getPictureLogicalPath()+filenames.get(i));
            }
            bailmentDetailVO.setPictures(filenames);
            generalResponse.setCode(200);
            generalResponse.setMsg("获取数据成功！");
            generalResponse.setData(bailmentDetailVO);
        } catch (Exception e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("获取数据失败！");
        }

        return generalResponse;
    }

    /**
     * 删除寄养数据
     * @param bailmentDataId     寄养数据id
     * @param userId 用户id
     * @return
     */
    @Override
    public GeneralResponse deleteBailmentData(Long bailmentDataId, String userId) {
        GeneralResponse generalResponse = new GeneralResponse();

        try {
//            BailmentData bailmentData = bailmentDataMapper.selectBailmentData(bailmentDataId);
//            if(bailmentData.getUserId().equals(userId)) {
//                // 删除图片文件
//                List<String> filenames = pictureMapper.selectFilenames(bailmentDataId);
//                for (int i = 0; i < filenames.size(); i++) {
//                    File file = new File(PathUtils.getPicturePhysicalPath() + filenames.get(i));
//                    file.delete();
//                }
//                // 删除数据库数据
                bailmentDataMapper.deleteBailmentData(bailmentDataId);
                generalResponse.setCode(200);
                generalResponse.setMsg("删除成功！");
//            }else {
//                generalResponse.setCode(401);
//                generalResponse.setMsg("无权限删除该数据！");
//            }
        } catch (Exception e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("删除失败！");
        }
        return generalResponse;
    }

    /**
     * 恢复删除寄养数据
     * @param bailmentDataId     寄养数据id
     * @param userId 用户id
     * @return
     */
    @Override
    public GeneralResponse hfBailmentData(Long bailmentDataId, String userId) {
        GeneralResponse generalResponse = new GeneralResponse();

        try {
            bailmentDataMapper.hfBailmentData(bailmentDataId);
            generalResponse.setCode(200);
            generalResponse.setMsg("恢复成功！");
        } catch (Exception e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("恢复失败！");
        }
        return generalResponse;
    }



    /**
     * 搜索寄养数据业务
     * @param searchBailmentDataDTO 搜索条件
     * @return
     */
    @Override
    public GeneralResponse searchBailmentData(SearchBailmentDataDTO searchBailmentDataDTO) {
        GeneralResponse generalResponse = new GeneralResponse();
        String keyWord = searchBailmentDataDTO.getKeyWord();
        // 如果关键词不为空,则在每个字符中间加上 % 进行模糊查询
        if(keyWord != null && !("".equals(keyWord))) {
            StringBuffer stringBuffer = new StringBuffer(keyWord);
            int length = stringBuffer.length();
            for (int i = 0; i < length + 1; i++) {
                stringBuffer.insert(2*i,"%");
            }
            searchBailmentDataDTO.setKeyWord(stringBuffer.toString());
        }

        try {
            PageHelper.startPage(searchBailmentDataDTO.getPageNum(),searchBailmentDataDTO.getPageSize());
            List<SearchBailmentDataVO> searchBailmentDataVOs = bailmentDataMapper.selectSearchBailmentDataVO(searchBailmentDataDTO);
            PageInfo<SearchBailmentDataVO> searchBailmentDataVOPageInfo = new PageInfo<>(searchBailmentDataVOs);

            for (int i = 0; i < searchBailmentDataVOPageInfo.getList().size(); i++) {
                String filename = pictureMapper.selectFistFilename(searchBailmentDataVOPageInfo.getList().get(i).getId());
                searchBailmentDataVOPageInfo.getList().get(i).setPicture(PathUtils.getPictureLogicalPath() + filename);
            }
            generalResponse.setCode(200);
            generalResponse.setMsg("搜索成功!");
            generalResponse.setData(searchBailmentDataVOPageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            generalResponse.setCode(500);
            generalResponse.setMsg("搜索失败!");

        }
        return generalResponse;
    }
}
